#include "list.h"

#include <string.h>

int initList(list *l, unsigned int sizeCell)
{
    l->size = 0;

    if ( !(l->data = (void *)malloc(sizeCell*SIZE_LIST)))
        return 0;

    l->capacity = SIZE_LIST;
    l->sizeCell = sizeCell;

    return 1;	
}

void endList(list *l)
{
    if (l->data != NULL)
        free(l->data);

    l->size = l->capacity = 0;
    l->data = NULL;
}

int insertList(list *l, void *data)
{
    if (l->capacity == l->size)
        if ( !reallocMemory(l))
            return 0;
    
    memcpy((l->data + l->sizeCell*l->size), data, l->sizeCell);

    l->size++;    

    return 1;
}

int reallocMemory(list *l)
{
    if ( !(l->data = (void *)realloc(l->data, l->sizeCell*l->capacity*2)))
        return 0;

    l->capacity *= 2;

    return 1;
}


void cleanList(list *l)
{
    l->size = 0;
}

int isList(list *l, void *data)
{
    unsigned int i = 0;

    for (i = 0; i < l->size; i++)
        if (!memcmp(getElementList(l, i), data, l->sizeCell))
            return 1;

    return 0;
}

int checkStatusList(list *l)
{
    return l->size == l->capacity;
}

void * getElementList(list *l, unsigned int location)
{
    if (location >= l->size)
        return NULL;

    return l->data+location*l->sizeCell;
}
